package com.yc.thread;

import java.util.Random;

/**
 * @program: concurrent
 * @description:
 * @author: zy
 * @create: 2022-01-10 13:48
 */
public class Test15_synchronized {

    public static void main(String[] args) {
        SellTickOp sto = new SellTickOp(100);
        for( int i=1;i<=100;i++) {
            Thread counter1 = new Thread(sto, "柜员======"+i);
            counter1.start();
        }

    }
}

// synchronized 同步
//卖票的任务
class SellTickOp implements Runnable {
    int tickets;   //总票数
    Random r = new Random();

    public SellTickOp(int tickets) {
        this.tickets = tickets;
    }

    @Override
    public void run() {
        while (  true   ) {
            synchronized (this) {      //块级同步                  同步两种:  方法级              synchronized   void  方法名(){}
                //块级： 将同步加到要同步的代码上,   注意   synchronized(    参照对象  ){   }
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "在sell第" + (tickets--) + "张票");
                    try {
                        //模拟出票的时间
                        Thread.sleep(   100  );
                        //wait(    r.nextInt( 100) );   //必须与  synchronized结合使用.

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    return;
                }
            }
        }

    }
}
